package com.xzcs.shiro;

import com.xzcs.util.web.RequestUtils;
import com.xzcs.util.web.ResponseUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc: 
 * @author: chang
 * @date: 2017/6/7
 */
public class MyPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {
    public Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        Subject subject = this.getSubject(request, response);
        if(subject.getPrincipal() == null) {
            if (RequestUtils.isAjaxRequest((HttpServletRequest)request)) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("result", "0");
                map.put("msg", "您尚未登录或登录超时,请重新登录!");
                ResponseUtils.writeJson(map, (HttpServletResponse)response);
            } else {
                this.saveRequestAndRedirectToLogin(request, response);
            }
        } else {
            if (RequestUtils.isAjaxRequest((HttpServletRequest)request)) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("result", "0");
                map.put("msg", "您没有权限访问该资源!");
                ResponseUtils.writeJson(map, (HttpServletResponse)response);
            } else {
                String unauthorizedUrl = this.getUnauthorizedUrl();
                if(StringUtils.hasText(unauthorizedUrl)) {
                    WebUtils.issueRedirect(request, response, unauthorizedUrl);
                } else {
                    WebUtils.toHttp(response).sendError(401);
                }
            }
        }

        return false;
    }
}
